import { login as apiLogin, type LoginData } from "~/composables/api/auth";
import { getInfo } from "~/composables/api/admin/system/user";
import { tree } from "~/composables/api/admin/system/menu";
import type { RouteRecord } from "vue-router";

export function getToken() {
  const cookie = useCookie<Token>(CookieAuthTokenKey);
  return cookie.value;
}

export async function useLogin(data: LoginData) {
  const r = await apiLogin(data);
  if (r.success) {
    const token = r.data;
    const user = useUserStore();
    user.setToken(token.accessToken);
    const cookie = useCookie<Token>(CookieAuthTokenKey, {
      maxAge: token.refreshExpirationTime - Date.now(),
    });
    cookie.value = token;
    await useInitUser(token);
    return token;
  }
  return null;
}

export async function useInitUser(token: Token) {
  const user = useUserStore();
  if (token.accessToken) {
    const { data } = await getInfo();
    user.setUser(data);
    const menuTreeR = await tree(data.menus);
    const router = useRouter();
    const routeMap = new Map<string, RouteRecord>();
    const menuTree = menuTreeR.data;
    router.getRoutes().forEach((route) => {
      routeMap.set(route.name as string, route);
    });
    replenishMenuPath(menuTree, routeMap);
    user.setMenuTree(menuTree);
  }
}

export async function useLogout() {
  const user = useUserStore();
  const cookie = useCookie(CookieAuthTokenKey);
  cookie.value = null;
  user.clearUser();
}
